package com.itcm.skymail.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcm.common.constant.ProductConstant;
import com.itcm.common.to.SkuHasStockVo;
import com.itcm.common.to.SkuReductionTo;
import com.itcm.common.to.SpuBoundTo;
import com.itcm.common.to.es.SkuEsModel;
import com.itcm.common.utils.PageUtils;
import com.itcm.common.utils.Query;
import com.itcm.common.utils.R;
import com.itcm.skymail.product.dao.SpuInfoDao;
import com.itcm.skymail.product.entity.*;
import com.itcm.skymail.product.feign.CouponFeignService;
import com.itcm.skymail.product.feign.SearchFeignService;
import com.itcm.skymail.product.feign.WareFeignService;
import com.itcm.skymail.product.service.*;
import com.itcm.skymail.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInof(SpuSaveVo vo) {
        // 1. 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);

        // 2. 保存spu的描述图片信息 pms_spu_info_desc
        Long spuId = spuInfoEntity.getId();
        Long brandId = spuInfoEntity.getBrandId();
        Long catalogId = spuInfoEntity.getCatalogId();

        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);

        // 3. 保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.savaImages(spuId, images);

        // 4. 保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        productAttrValueService.saveBaseAttrs(spuId, baseAttrs);

        // 5. 保存spu的积分信息 skymail_sms -> sms_spu_bounds
        // 需要调用远程服务
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setSpuId(spuId);
        spuBoundTo.setBuyBounds(bounds.getBuyBounds());
        spuBoundTo.setGrowBounds(bounds.getGrowBounds());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }


        // 6. 保存当前spu对应的所有sku信息：
        // 6.1. sku的基本信息 pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setBrandId(brandId);
                skuInfoEntity.setCatalogId(catalogId);
                skuInfoEntity.setSaleCount(0L);

                // 遍历获取默认图片
                String defaultImgUrl = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImgUrl = image.getImgUrl();
                    }
                }

                skuInfoEntity.setSkuDefaultImg(defaultImgUrl);
                skuInfoService.save(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();

                // 6.2. sku的图片信息 pms_sku_images
                List<Images> images1 = sku.getImages();
                log.info("提交的skuImages : {}", images1);
                List<SkuImagesEntity> skuImagesEntities = images1.stream().map(skuImage -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(skuImage.getImgUrl());
                    skuImagesEntity.setDefaultImg(skuImage.getDefaultImg());
                    return skuImagesEntity;
                }).filter(item -> !StringUtils.isEmpty(item.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                log.info("处理后的skuImages : {}", skuImagesEntities);

                // 6.3. sku的销售属性信息 pms_sku_attr_value
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);

                // 6.4. sku的优惠、满减等信息 skymial_sms -> sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                // 需要调用远程服务
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);

                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(status) && !brandId.equalsIgnoreCase("0")) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !catelogId.equalsIgnoreCase("0")) {
            wrapper.eq("catalog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> obj.eq("id", key).or().like("spu_name", key));
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /*
     * 商品上架
     */
    @Override
    public void up(Long spuId) {
        // 组装es所需数据
        List<SkuEsModel> list = new ArrayList<>();
        // 查出当前spuId所对应的所有sku信息，品牌名。
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        System.out.println("----------");
        System.out.println(skus);
        System.out.println("-----------");
        // 查询当前spu对应的所有可以被检索的规格属性
        List<ProductAttrValueEntity> attrValues = productAttrValueService.listForSpuId(spuId);
        List<Long> baseAttrIds = attrValues.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.filterSearchAttrIds(baseAttrIds);
        // 转换成set 方便判断
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> attrsList = attrValues.stream()
                .filter(o -> idSet.contains(o.getAttrId()))
                .map(o -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(o, attrs);
                    return attrs;
                })
                .collect(Collectors.toList());
        // 发送远程调用，库存系统查询是否有库存
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> hasStockMap = null;
        try {
            List<SkuHasStockVo> skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            hasStockMap = skuHasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常: {}", e.getMessage());
        }

        for (SkuInfoEntity skuInfoEntity : skus) {
            System.out.println("----------");
            System.out.println(skuInfoEntity);
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            // 属性名不一致 和 不存在的都需要单独设置
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            // 发送远程调用，库存系统查询是否有库存
            if (hasStockMap == null) {
                // 库存服务出问题时 默认库存状态为true
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(hasStockMap.get(skuInfoEntity.getSkuId()));
            }
            // 热度评分 简单处理 刚上架为0
            skuEsModel.setHotScore(0L);
            // 设置品牌和分类信息
            BrandEntity brand = brandService.getById(skuInfoEntity.getBrandId());
            CategoryEntity category = categoryService.getById(skuInfoEntity.getCatalogId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());
            skuEsModel.setCatalogName(category.getName());
            // 设置规格信息
            skuEsModel.setAttrs(attrsList);
            list.add(skuEsModel);
        }
        // 将数据保存到es
        // 调用search远程服务 来将数据发送到es

        R r = searchFeignService.productUp(list);

        if (r.getCode() == 0) {
            // 远程调用成功
            // 修改当前spu状态为已上架
            this.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 远程调用失败 是否有重试机制？
            // Feign 调用流程
            /**
             * 1. 构造请求数据，将对象转为json
             *      RequestTemplate template = buildTemplateFromArgs.create(argv);
             * 2. 发送请求并执行 执行成功会解码响应数据
             *      executeAndDecode(template)
             * 3. 执行请求会有重试机制 默认重试器最大重试次数5
             *      while (true){
             *          try{
             *              executeAndDecode(template)
             *          }catch (){
             *              try{
             *                  retryer.continueOrPropagate(e);
             *              }catch{
             *                  throw ex;
             *              }
             *              continue;
             *          }
             *      }
             */
        }
    }

    @Override
    public void updateSpuStatus(Long spuId, int code) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setId(spuId);
        spuInfoEntity.setPublishStatus(code);
        spuInfoEntity.setUpdateTime(new Date());
        this.updateById(spuInfoEntity);

    }
}